import { useState, useCallback, useMemo, useEffect } from "react";
import { Text, View } from "@tarojs/components";
import { observer } from 'mobx-react';
import i18n from "i18n-js";
import Taro from '@tarojs/taro';
import { GStyleSheet, DynamicColors } from "@/utils/DarkMode";
import { useDeviceListStore } from '@/hooks';
import homeModel from '@/models/homes';
import deviceListModel from '@/models/deviceList';
import Toast from "@/utils/Toast";
import { GButton } from '@/components/GButton';
import FlexScrollView from '@/components/FlexScrollView';
import CheckBox from '@/components/CheckBox';
import Alert from "@/components/Alert";
import PageContainer from "@/components/PageContainer";
import { isSameDevice } from "@/utils";
import DeviceItem from '../home/deviceList/deviceItem';
import { toJS } from "mobx";


const dstyle = GStyleSheet.create({
  list: {
    paddingTop: 20,
    paddingLeft: 20,
    paddingRight: 20,
  },
  bottom: {
    marginTop: 20,
    marginBottom: 20,
  },
  deleteText: {
    color: DynamicColors.tintColor
  },
});


const DeviceList = () => {
  const { data } = useDeviceListStore();
  console.log('deviceList', data.length);
  const styles = dstyle.useDynamicStyle();
  const [selList, setSelList] = useState<IDevice[]>([]);
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [isCheckAll, setIsCheckAll] = useState(false)

  useEffect(() => {
    if (selList.length === data.length) {
      setIsCheckAll(true)
    } else {
      setIsCheckAll(false)
    }
  }, [selList, data])

  // 防止在这个页面有设备列表变化
  const selectList = useMemo(() => {
    return selList.filter(i => data.findIndex(d => isSameDevice(i, d)) > -1)
  }, [data, selList]);

  const changeSelected = useCallback(({ device, isSelected }: { device: IDevice, isSelected: boolean }) => {
    const index = selList.findIndex(i => isSameDevice(i, device));
    if (isSelected) {
      if (index < 0) {
        const arr = selList.concat([device]);
        setSelList(arr);
      }
    } else {
      if (index > -1) {
        selList.splice(index, 1);
        setSelList([...selList]);
      }
    }
  }, [selList]);

  const selectAll = useCallback(() => {
    const checkAll = !isCheckAll;
    setIsCheckAll(checkAll)
    if (checkAll) {
      setSelList(toJS(data));
    } else {
      setSelList([]);
    }
  }, [changeSelected, setSelList, data, isCheckAll])

  const showDelAlert = useCallback(() => {
    setDeleteAlert(true);
  }, []);

  const hideDelAlert = useCallback(() => {
    setDeleteAlert(false);
  }, []);

  const deleteDevice = useCallback(async () => {
    hideDelAlert();
    Toast.loading('');
    await homeModel.deleteDevices(selectList);
    deviceListModel.getDeviceList();
    Toast.hideLoading();
    Taro.navigateBack();
  }, [selectList, hideDelAlert])

  return (
    <PageContainer title={i18n.t('DELETE_DEVICE')}>
      <View style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <View style={{display: 'flex', justifyContent: 'flex-end', paddingRight: 42, paddingTop: 20}}>
          <View style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Text>{i18n.t('全选')}</Text>
            <CheckBox checked={isCheckAll} onPress={selectAll} />
          </View>
        </View>
        <FlexScrollView id='deleteScrollList' scrollStyle={styles.list}>
          {data.map((device) => {
            const isSelected = selectList.findIndex(i => isSameDevice(i, device)) > -1;
            return <DeviceItem key={device.did} device={device} onClick={() => { changeSelected({ device, isSelected: !isSelected }) }} renderRight={<CheckBox checked={isSelected} />} />
          })}
            <View style={{ height: 20 }} />
        </FlexScrollView>
        <View style={styles.bottom}>
          <GButton text={i18n.t('DELETE')} onPress={showDelAlert} disabled={selectList.length < 1} />
        </View>
      </View>
      <Alert
        title={i18n.t('SURE_TO_DELETE')}
        visible={deleteAlert}
        onCancel={hideDelAlert}
        onConfirm={deleteDevice}
        okText={<Text style={styles.deleteText}>{i18n.t('DELETE')}</Text>}
      />
    </PageContainer>
  );
};

export default observer(DeviceList);
